<?php
class JSON {
    private $request_data = array();
    private $response_data = array();
    private $errors = array();
    private $jsoncb;
    private $relocate;
    private $state = true;


    public function __construct() {
        $this->jsoncb = Arr::getValue($_REQUEST, 'jsoncb', '');
    }

    public function __get($varname) {
        return Arr::getValue($this->response_data, $varname);
    }

    public function __set($varname, $value) {
        $this->sendVar($varname, $value);
    }

    public function __toString() {
        return $this->getEncodedData();
    }




    public function readVar($varname, $defValue='') {
        $val = Arr::getValue($_POST, $varname, $defValue);
        $this->request_data[$varname] = $val;
        return $val;
    }

    public function sendVar($varname, $value) {
        if ($varname) $this->response_data[$varname] = $value;
    }

    public function error($message) {
        $this->errors[] = $message;
        $this->state = false;
        return $this;
    }

    public function reLocate($url) {
        $this->relocate = $url;
    }

    public function getState() {
        return $this->state;
    }
    
    public function getErrorString() {
        return join('<br>',$this->errors);
    }



    public function getEncodedData() {
        $result = new stdClass();
        $result->state = $this->state;
        $result->message = $result->state? '' : $this->getErrorString();
        $result->response_data = $this->response_data;
        $result->request_data = $this->request_data;
        $result->relocate = $this->relocate;

        $result->logged = Auth::isLogged();
        $result->token = $result->logged? 'hidden' : Auth::getToken();


        if ($this->jsoncb) return $this->jsoncb."(".json_encode($result).");";
        else return json_encode($result);
    }


}

?>